﻿package com.ghostmonk.selectedWork.utils 
{	
	import com.ghostmonk.selectedWork.globals.ConfigVariables;
	import com.greensock.TweenLite;
	
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	
	public class StillImageLoader extends Sprite 
	{
		private var _loadProgressBar:LoadingBar;
		private var _loadPercent:EmbeddedTextField;
		private var _overLay:Sprite;
		private var _loader:Loader;
		
		public function StillImageLoader() 
		{	
			_loadProgressBar = new LoadingBar();
			_loadPercent = new EmbeddedTextField( ConfigVariables.HELVETICA_NEUE_LT, 14, 0xFFFFFF );
			_overLay = new Sprite();
			_loader = new Loader();
			
			addChild( _loader );

			_loadProgressBar.x = 20;
			_loadProgressBar.y = 100;
			_loadPercent.x = _loadProgressBar.x;
			_loadPercent.y = _loadProgressBar.y - 25;		
		}
		
		public function loadNewImg( imageURL:String ):void 
		{	
			_loader.unload();
			_loader.alpha = 0;
			_loader.load( new URLRequest( imageURL ) );
			
			_loader.contentLoaderInfo.addEventListener( Event.OPEN, onOpen) ;
			_loader.contentLoaderInfo.addEventListener( ProgressEvent.PROGRESS, onProgress ); 
			_loader.contentLoaderInfo.addEventListener( Event.COMPLETE, onComplete );
			
			_overLay.graphics.clear();	
		}
		
		private function onOpen( e:Event ) : void 
		{	
			addChild( _loadProgressBar );
			addChild( _loadPercent );
			_loadPercent.text = "0%";	
		}
		
		private function onProgress( e:ProgressEvent ) : void 
		{	
			var percent:Number = int( e.bytesLoaded / e.bytesTotal * 100 );
			_loadProgressBar.gotoAndStop( percent );
			_loadPercent.text = "" + percent + "%";	
		}
		
		private function onComplete( e:Event ) : void 
		{	
			removeChild( _loadProgressBar );
			removeChild( _loadPercent );
			_overLay.graphics.beginFill( 0x000000, 0.8 );
			_overLay.graphics.drawRect( 0, 0, _loader.contentLoaderInfo.width, _loader.contentLoaderInfo.height );
			_overLay.graphics.endFill();
			addChild( _overLay );
			_overLay.alpha = 0;
			_overLay.x = _loader.x;
			_overLay.y = _loader.y;
			
			_loader.contentLoaderInfo.removeEventListener( Event.INIT, onOpen );
			_loader.contentLoaderInfo.removeEventListener( ProgressEvent.PROGRESS, onProgress ); 
			_loader.contentLoaderInfo.removeEventListener( Event.COMPLETE, onComplete );
			TweenLite.to( _loader, 0.5, { alpha:1 } );	
		}
		
		public function tweenOverLay( overlay:Boolean ) : void 
		{	
			var tAlpha:Number = overlay ? 0.8 : 0;
			TweenLite.to( _overLay, 0.5, { alpha:tAlpha } );	
		}
	}
}